package com.windsea.relationshipmining.activity;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.windsea.relationshipmining.R;
import com.windsea.relationshipmining.api.TransferManager;
import com.windsea.relationshipmining.database.DBServiceHandler;
import com.windsea.relationshipmining.database.DBUserData;
import com.windsea.relationshipmining.model.Relationship;

public class RelationChooserActivity extends Activity implements
		OnItemClickListener, OnClickListener {
	DBUserData dbUserData;
	Relationship relationship = null;
	ArrayList<Relationship> arr;
	private ListView lv;
	RelationshipAdapter adapter;
	TextView tvNum;
	Button btnSend;
	private boolean isOk = false;

	@SuppressLint("ShowToast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		cancelNotification(10001);
		setContentView(R.layout.activity_relationshipchooser);
		RelationChooserGuideDialog rcg = new RelationChooserGuideDialog(this);
		rcg.show();
		arr = new ArrayList<Relationship>();
		dbUserData = new DBUserData(this);
		dbUserData.open();

		lv = (ListView) findViewById(R.id.listRelationChooser);

		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(this);
		Cursor mCursor;

		mCursor = dbUserData.getContact();
		String label = null;
		if (mCursor != null && mCursor.getCount() != 0 && mCursor.moveToFirst()) {

			do {
				if (mCursor.getInt(mCursor.getColumnIndex("NumOfCall")) == 1
						|| mCursor.getInt(mCursor.getColumnIndex("NumOfSMS")) == 1) {

					if (mCursor.getInt(mCursor.getColumnIndex("Family")) == 1
							|| mCursor.getInt(mCursor.getColumnIndex("Work")) == 1
							|| mCursor.getInt(mCursor
									.getColumnIndex("Acquaintance")) == 1
							|| mCursor.getInt(mCursor.getColumnIndex("Friend")) == 1
							|| mCursor.getInt(mCursor.getColumnIndex("Other")) == 1) {
						label = "Đã dán ";
					} else {
						label = null;
					}
					arr.add(new Relationship(mCursor.getString(mCursor
							.getColumnIndex("ContactID")), mCursor
							.getString(mCursor.getColumnIndex("Name")), label));
				}
			} while (mCursor.moveToNext());
			dbUserData.close();
		}
		int count = 0;
		if (arr != null) {
			for (int i = 0; i < arr.size(); i++) {
				if (arr.get(i).getContactRelation() != null) {
					count++;
				}
			}
		}
		if (count != 0 && count == arr.size()) {
			isOk = true;
		} else {
			isOk = false;
		}
		tvNum = (TextView) findViewById(R.id.numberchosed);
		tvNum.setText("Đã gán nhãn: " + count + "/ " + arr.size() + " liên hệ");
		adapter = new RelationshipAdapter(getApplicationContext(), arr);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(final AdapterView<?> arg0, View arg1, int position,
			long id) {
		ItemContactDialog mDialog = new ItemContactDialog(this, arr.get(
				position).getContactid(), arr, tvNum, isOk, adapter);
		mDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.relationchoosermenu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.help:
			Toast.makeText(
					getApplicationContext(),
					"Bạn hãy chọn từng liên hệ: mối quan hệ với bạn, chênh lệch tuổi, bạn của bạn trên facebook.",
					Toast.LENGTH_LONG).show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public void onClick(View v) {
		if (v == btnSend) {
			if (isOk) {
				DBUserData dbUserData = new DBUserData(getApplicationContext());
				dbUserData.open();
				Cursor cur2 = null;
				cur2 = dbUserData.getInfo();
				if (isNetworkAvailable() && cur2 != null && cur2.moveToFirst()) {
					finish();

					new Thread(new Runnable() {

						@Override
						public void run() {
							// Log.d(TAG, "Data is transfering...");
							TransferManager trMana = new TransferManager(
									getApplicationContext());
							// trMana.exportDB();
							boolean status = trMana.pushToServer("userdata");
							boolean databasewiped = false;
							if (status) {
								databasewiped = trMana.wipeDatabase();
								if (databasewiped) {
									DBServiceHandler dbHandle = new DBServiceHandler(
											getApplicationContext());
									dbHandle.open();
									dbHandle.insertRelationDone("done");
									dbHandle.close();
									Intent intent = new Intent(
											getApplicationContext(),
											HelpActivity.class);
									startActivity(intent);
								} else {
									Toast.makeText(
											getApplicationContext(),
											"Gửi dữ liệu thất bại, hãy kiểm tra lại kết nối internet.",
											Toast.LENGTH_LONG).show();
								}
							}

						}
					}).start();

				} else if (!cur2.moveToFirst()) {
					// --------------NOTIFICATION--------------------------------------------
					Intent intent = new Intent(getApplicationContext(),
							MainActivity.class);
					PendingIntent pIntent = PendingIntent.getActivity(
							getApplicationContext(), 0, intent, 0);

					// Build notification
					NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
					Notification noti = new Notification(
							com.windsea.relationshipmining.R.drawable.ic_launcher,
							"Xin hãy điền thông tin cá nhân", System
									.currentTimeMillis());
					noti.setLatestEventInfo(getApplicationContext(),
							"RelationshipMining",
							"Bạn hãy điền thông tin cá nhân", pIntent);

					noti.defaults |= Notification.DEFAULT_SOUND;
					// Hide the notification after its selected
					noti.flags |= Notification.FLAG_AUTO_CANCEL;

					notificationManager.notify(0, noti);
					// END OF NOTIFICATION -----------------------------------

				} else {
					// --------------NOTIFICATION--------------------------------------------
					Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
					PendingIntent pIntent = PendingIntent.getActivity(
							getApplicationContext(), 0, intent, 0);

					// Build notification
					NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
					Notification noti = new Notification(
							com.windsea.relationshipmining.R.drawable.ic_launcher,
							"Xin hãy bật kết nối dữ liệu", System
									.currentTimeMillis());
					noti.setLatestEventInfo(getApplicationContext(),
							"RelationshipMining",
							"Chương trình cần kết nối dữ liệu 3G hoặc wifi",
							pIntent);

					noti.defaults |= Notification.DEFAULT_SOUND;
					// Hide the notification after its selected
					noti.flags |= Notification.FLAG_AUTO_CANCEL;

					notificationManager.notify(0, noti);
					// END OF NOTIFICATION -----------------------------------

				}
			} else {
				Toast.makeText(getBaseContext(),
						"Bạn chưa gán hết nhãn cho danh sách",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			finish();
			Intent intent = new Intent(getBaseContext(), MainActivity.class);
			startActivity(intent);
		}
		return super.onKeyDown(keyCode, event);
	}

	public void cancelNotification(int notificationId) {

		if (Context.NOTIFICATION_SERVICE != null) {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager nMgr = (NotificationManager) getApplicationContext()
					.getSystemService(ns);
			nMgr.cancel(notificationId);
		}
	}

	public boolean isNetworkAvailable() {
		getBaseContext();
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

}
